#!/bin/bash
# ----------------------------------------------------------------------
# use : bash higress_k3_install.sh
# ----------------------------------------------------------------------

# abort on errors
set -e

port="$1"

# 安装docker
if ! [ -x "$(command -v docker)" ]; then
  echo '检测到 Docker 尚未安装，正在尝试安装 Docker ...'

  if [ -x "$(command -v yum)" ]; then
    sudo yum install -y python3-pip yum-utils device-mapper-persistent-data lvm2
    sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    yum list docker-ce --showduplicates | sort -r
    sudo yum install docker-ce
  else
    sudo apt-get update
    sudo dpkg --configure -a
    sudo apt-get install python3-pip apt-transport-https ca-certificates curl software-properties-common
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
    sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
    sudo apt-get update
    sudo apt-get install docker-ce
  fi

  # 启动docker和开机自启动
  sudo systemctl start docker
  sudo systemctl enable docker
fi


 # 安装 k3s
if ! [ -x "$(command -v kubectl)" ]; then
  echo '检测到 k3s 尚未安装，正在尝试安装 k3s ...'
  curl -sfL https://rancher-mirror.rancher.cn/k3s/k3s-install.sh | INSTALL_K3S_MIRROR=cn INSTALL_K3S_EXEC="--docker --disable=traefik" sh -
  
  mkdir -p /root/.kube/
  cat /etc/rancher/k3s/k3s.yaml > /root/.kube/config
  export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
  
  systemctl daemon-reload
  systemctl enable k3s
  
  echo '安装k3s 可视化kuboard ...'
  kubectl apply -f https://addons.kuboard.cn/kuboard/kuboard-v3-swr.yaml
fi

 # 安装 helm
if ! [ -x "$(command -v helm)" ]; then
  echo '检测到 helm 尚未安装，正在尝试安装 helm 3.13.3 ...'
  
  if [[ ! -f "/root/helm-v3.13.3-linux-amd64.tar.gz" ]]; then
     wget --no-check-certificate https://get.helm.sh/helm-v3.13.3-linux-amd64.tar.gz
  fi
  tar -zxvf helm-v3.13.3-linux-amd64.tar.gz
  mv linux-amd64/helm /usr/local/bin/helm
fi


 # 开始安装higress
if [ -x "$(command -v kubectl)" -a -x "$(command -v helm)" ]; then
  docker version
  helm version
  
  helm repo add higress.io https://higress.io/helm-charts
  helm install higress -n higress-system higress.io/higress --create-namespace --render-subchart-notes
  
  #监控套件
  #helm install higress -n higress-system higress.io/higress --create-namespace --render-subchart-notes --set higress-console.o11y.enabled=true

else

  if ! [ -x "$(command -v kubectl)" ]; then
    echo 'k3s 安装失败，请检测您当前的环境（或网络）是否正常。'
  fi


  if ! [ -x "$(command -v helm)" ]; then
    echo 'helm 安装失败，请检测您当前的环境（或网络）是否正常。'
  fi

fi

rm -f higress_k3_install.sh
